package com.lw.lost.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.lw.lost.R
import com.lw.lost.databinding.ItemFriendRequestBinding
import com.lw.lost.models.FriendRequest

class FriendRequestAdapter(
    private val onAccept: (FriendRequest) -> Unit,
    private val onReject: (FriendRequest) -> Unit
) : ListAdapter<FriendRequest, FriendRequestAdapter.ViewHolder>(DiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemFriendRequestBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(
        private val binding: ItemFriendRequestBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(request: FriendRequest) {
            binding.apply {
                tvName.text = request.senderName
                tvMessage.text = request.message
                tvTime.text = request.createTime

                // 加载头像
                Glide.with(ivAvatar)
                    .load(request.senderAvatar)
                    .circleCrop()
                    .placeholder(R.drawable.ic_avatar_default)
                    .error(R.drawable.ic_avatar_default)
                    .into(ivAvatar)

                // 设置按钮点击事件
                btnAccept.setOnClickListener { onAccept(request) }
                btnReject.setOnClickListener { onReject(request) }
            }
        }
    }

    private class DiffCallback : DiffUtil.ItemCallback<FriendRequest>() {
        override fun areItemsTheSame(oldItem: FriendRequest, newItem: FriendRequest) =
            oldItem.requestId == newItem.requestId

        override fun areContentsTheSame(oldItem: FriendRequest, newItem: FriendRequest) =
            oldItem == newItem
    }
} 